package com.managertrade.controller;

import com.managertrade.common.ErrorCode;
import com.managertrade.common.Result;
import com.managertrade.common.ServiceException;
import com.managertrade.dto.LoginRequestDTO;

import com.managertrade.dto.vo.LoginResponseVO;
import com.managertrade.dto.vo.MenuVO;
import com.managertrade.dao.mysql.entity.SysMenu;
import com.managertrade.dao.mysql.entity.SysRole;
import com.managertrade.dao.mysql.entity.SysUser;
import com.managertrade.dao.mysql.repository.SysRoleMenuRepository;
import com.managertrade.dao.mysql.repository.SysRoleRepository;
import com.managertrade.dao.mysql.repository.SysUserRepository;
import com.managertrade.dao.mysql.repository.SysUserRoleRepository;
import com.managertrade.service.impl.MenuService;
import com.managertrade.service.impl.RoleService;
import com.managertrade.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@CrossOrigin // 支持跨域请求
public class AuthController {
    @Resource
    private SysUserRepository sysUserRepository;
    @Autowired
    MenuService menuService;
    @Autowired
    SysRoleRepository sysRoleRepository;
    @Autowired
    SysUserRoleRepository sysUserRoleRepository;
    @Autowired
    SysRoleMenuRepository sysRoleMenuRepository;
    @Autowired
    RoleService roleService;

    @PostMapping("/login")
    public Result<LoginResponseVO> login(@RequestBody LoginRequestDTO dto) {
        SysUser user = sysUserRepository.findByUsername(dto.getUsername())
                .orElseThrow(() ->new ServiceException(ErrorCode.USER_NOT_FOUND));

        if (!user.getPassword().equals(dto.getPassword())) {
            throw new ServiceException(ErrorCode.PASSWORD_ERROR);
        }
        //获取用户角色
        List<SysRole> roleUserList = roleService.findSysRoleByUser(user.getId());
        if(CollectionUtils.isEmpty(roleUserList)){
            throw new ServiceException(ErrorCode.ROLE_CODE_NOT_FOUND);
        }

        String token = JwtUtil.generateToken(user.getId(), user.getUsername());
        //获取权限
        List<SysMenu> menuByUserId = menuService.getMenuByUserId(user.getId());
        LoginResponseVO vo = new LoginResponseVO();
        vo.setToken(token);
        vo.setUsername(user.getUsername());
        vo.setNickname(user.getNickname());
        vo.setRoles(roleUserList.stream().map(k->k.getCode()).collect(Collectors.toList()));
        vo.setPermissions(menuByUserId.stream().filter(k-> Objects.equals(k.getType(),2)).map(k->k.getPerms()).collect(Collectors.toList()));
        // 从数据库或服务获取菜单
        List<MenuVO> menuList = menuService.getMenuTreeByUserId(user.getId());
        vo.setMenuList(menuList);
        return Result.success(vo);
    }
}

